package com.esun.server.aspect;

import cn.dev33.satoken.stp.StpUtil;
import com.esun.common.enums.LoginUserInfo;
import com.esun.common.enums.UserAgent;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Set;

/**
 * 域切面
 * @author John.xiao
 * @date 2021/8/13 9:22
 */
@Slf4j
@Component
@Aspect
public class RequestAspect {
	private static final Set<String> WHITELIST = Sets.newHashSet("/v1/login/login");

	@Around("execution(* com.esun.server.controller.*.*(..))")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
		String path = request.getRequestURI();
		if (WHITELIST.contains(path)){
			return joinPoint.proceed();
		}
		//从header中获取domainId
		String domainId = request.getHeader("DOMAIN_ID");
		String corpId = request.getHeader("CORP_ID");
		log.info("request DomainId :{}",domainId);
		String userId = StpUtil.getLoginIdAsString();
		String token = StpUtil.getTokenValue();
		LoginUserInfo loginUserInfo = LoginUserInfo.builder().userId(userId).domainId(domainId).token(token).corpId(corpId).build();
		UserAgent.set(loginUserInfo);
		return joinPoint.proceed();
	}

}
